// 判断是否是所传接口之一
function contrastApi(url, apis = []) {
  for (let i = 0; i < apis.length; i++) {
    if (url.indexOf(apis[i]) >= 0) {
      return true;
    }
  }
  return false;
}

// 需要过滤showLoading的接口
const NO_SHOWLOADING_APIS = ['get/formId', '/spotFabulous', '/cancelFabulous', '/memberCollect', '/memberCancelCollect'];

// 创建请求
function createRequest(args, isform) {
  if (!contrastApi(args.url, NO_SHOWLOADING_APIS)) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
  }
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        console.log('======== request请求 ========');
        console.log(args);
        console.log('======== request请求成功 ========');
        console.log(res)
        wx.hideLoading();
        if (res.statusCode === 200) {
          // 请求成功
          if (res.data.status === 0) {
            resolve(res.data);
            return;
          }

          // 未授权验证
          if (res.data.status === 201) {
            getApp().showConfirm('提示', res.data.msg, false, function() {
              wx.navigateTo({
                url: '/pages/agent/authorization/authorization',
              })
            });
            return;
          }

          // 未绑定账号(客户账号)
          if (res.data.status === 202) {
            getApp().showConfirm('您还未登录', '请先登录再进行操作~', true,
              () => {
                if (getApp().globalData.openid) {
                  wx.navigateTo({
                    url: '/pages/agent/center/bind/bind',
                  })
                } else {
                  wx.navigateTo({
                    url: '/pages/agent/authorization/authorization',
                  })
                }
              },
              () => {
                wx.navigateBack();
              }, '暂不登录', '登录注册');
            reject(res);
            return;
          }

          // 会员未认证(通讯录插件)
          if (res.data.status === 203) {
            getApp().showConfirm('提示', res.data.msg, true, function() {
              wx.redirectTo({
                url: '/pages/agent/center/authentication/index',
              })
            }, () => {
              wx.navigateBack()
            }, '以后再说', '前往认证');
            return;
          }

          // 会员等待认证
          if (res.data.status === 204) {
            getApp().showConfirm('提示', res.data.msg, false, function() {
              wx.navigateBack();
            });
            return;
          }

          // 会员未通过
          if (res.data.status === 205) {
            getApp().showConfirm('提示', res.data.msg, true, function() {
              wx.redirectTo({
                url: '/pages/agent/center/authentication/index',
              })
            }, () => {
              wx.navigateBack()
            }, '以后再说', '重新认证');
            return;
          }

          // 未绑定账号信息(未绑定账号直接进入下一步)
          if (res.data.status === 206) {
            resolve(res.data);
            return;
          }

          // 员工端账号不存在或密码错误
          if (res.data.status === 207) {
            reject(res);
            return;
          }

          //  未授权登录
          if (res.data.status === 301) {
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            setTimeout(()=>{
              getApp().showConfirm('您还未登录', '请先登录再进行操作~', true,
                () => {
                  if (getApp().globalData.openid) {
                    wx.navigateTo({
                      url: '/pages/agent/center/bind/bind',
                    })
                  } else {
                    wx.navigateTo({
                      url: '/pages/agent/authorization/authorization',
                    })
                  }
                },
                () => {
                  wx.navigateBack({
                    fail: function(e){
                      console.log(e);
                      wx.reLaunch({
                        url: getApp().globalData.config['SwitchTabToAgentPageUrl']
                      })
                    }
                  })
                }, '暂不登录', '登录注册');
                wx.hideLoading();
            }, 1000);
            return;
          }

          // 手机号码已注册
          if (res.data.status === 311) {
            getApp().showConfirm('提示', res.data.msg, true, function() {
              wx.navigateTo({
                url: '/pages/agent/center/bind/bind?mobile=' + args.data.mobile,
              })
            });
            return;
          }

          // 其他异常
          getApp().showConfirm('提示', res.data.msg, false);
          reject(res);
        } else {
          // 服务器异常
          getApp().showConfirm('提示', res.data.errorMessage + ', 请刷新', false);
        }
      }
      obj.fail = function(res) {
        console.log('======== request请求 ========');
        console.log(args);
        console.log('======== request请求失败 ========');
        console.log(res);
        wx.hideLoading();
        reject(res)
      }
      if (!obj.header) {
        obj.header = {}
      }
      if (isform) {
        obj.header['content-type'] = "application/x-www-form-urlencoded";
      }
      var merge = extend(obj, args);
      wx.request(obj)
    })
  }
}

// 创建上传请求
function createUpload(args) {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        console.log('======== upload请求 ========');
        console.log(args);
        console.log('======== upload请求成功 ========');
        console.log(res)
        if (res.statusCode == 200) {
          var data = JSON.parse(res.data);
          if (data.status == 0) {
            resolve(data);
            return;
          }
        }
        reject(res)
      }
      obj.fail = function(res) {
        console.log('======== upload请求 ========');
        console.log(args);
        console.log('======== upload请求失败 ========');
        console.log(res)
        reject(res)
      }
      if (!obj.header) {
        obj.header = {}
      }
      var merge = extend(obj, args);
      wx.uploadFile(obj);
    })
  }
}

// 创建多请求
function createAll(args) {
  return Promise.all(args);
}

function extend(des, src, override) {
  if (src instanceof Array) {
    for (var i = 0, len = src.length; i < len; i++)
      extend(des, src[i], override);
  }
  for (var i in src) {
    if (override || !(i in des)) {
      des[i] = src[i];
    }
  }
  return des;
}

module.exports = {
  createRequest: createRequest,
  createUpload: createUpload,
  createAll: createAll,
  extend: extend
}